#pragma once
#include <iostream>
#include "Socket.hpp"
#include "Connection.hpp"
#include <sys/epoll.h>
// 对listensock来管理
// 也就是对应connection的recver方法在这里
class Listener
{

public:
    Listener(uint16_t port) : _port(port), _listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocket(_port);
    }
    int Sockfd()
    {
        return _listensock->sockfd();
    }
    void Accepter(Connection *conn)
    {
        // LOG(DEBUG, "%d listensock ready\n", conn->Sockfd());
        // ET
        while (1)
        {
            InetAddr addr;
            int code = 0;
            int sockfd = _listensock->Accepter(&addr, &code);
            if (sockfd > 0)
            {
                LOG(INFO, "get a new link:%s:%d,sockfd %d\n", addr.Ip().c_str(), addr.Port(), sockfd);
                conn->_R->AddConnection(sockfd, EPOLLIN | EPOLLET, addr, NORMALCONNECTION);//写事件不能常设，按需设，条件不满足再开
            }
            else
            {
                if (code == EWOULDBLOCK)
                {
                    LOG(INFO, "listensock accept finish\n");
                    break;
                }
                else if (code == EINTR)
                {
                    continue;
                }
                else
                {
                    LOG(ERROR, "accpet error\n");
                    break;
                }
            }
        }
    }
    ~Listener() {}

private:
    uint16_t _port;
    std::unique_ptr<TcpSocket> _listensock;
};
